package com.zxh.dubbozxh.framework.protocol.http;

import com.zxh.dubbozxh.framework.Invocation;
import com.zxh.dubbozxh.framework.register.LocalRegister;
import org.apache.commons.io.IOUtils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;

public class HttpServerHandler {

    public void handler(HttpServletRequest req, HttpServletResponse resp) {

        try {

            // 从请求中将Invocation对象拿出来，反序列化过程
            Invocation invocation = (Invocation)new ObjectInputStream(req.getInputStream()).readObject();
            // 此处获得的是接口名（服务名），一个接口可以有多个实现，版本1，版本2，如果要调用确定哪个版本，就再传入一个版本号
            // 此处要从接口名找实现类
            String interfaceName = invocation.getInterfaceName();
            String methodName = invocation.getMethodName();
            System.out.println(methodName);

            Class implClass = LocalRegister.get(interfaceName);
            Method method = implClass.getMethod(methodName, invocation.getParamType());

            String result = (String)method.invoke(implClass.newInstance(),invocation.getParams());

            IOUtils.write(result,resp.getOutputStream());


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
